/* file name  : STUNTServer.java
 * authors    : Saikat Guha <saikat@cs.cornell.edu>
 * created    : Sun 18 Sep 2005 02:50:31 AM EDT
 * copyright  : GNU Lesser General Public License version 2.1 or later
 *
 * Copyright (C) 2005 Saikat Guha <saikat@cs.cornell.edu>
 *
 * This library is free software; you can redistribute it and/or modify it under the terms
 * of the GNU Lesser General Public License as published by the Free Software Foundation;
 * either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this
 * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307 USA
 *
 */

package net.nutss.stunt;

import java.net.*;
import java.io.ObjectOutputStream;
import java.io.ByteArrayOutputStream;

/*
by casper not supported
import net.nutss.Control;
*/
import static net.nutss.Control.log;

/**
 * Returns the observed address and port to STUNT clients.
 *
 * @author Saikat Guha
 * @version 0.1
 */
public class STUNTServer extends Thread {

    /**
     * TCP passive socket that clients connect to
     */
    private ServerSocket server = null;

    /**
     * UDP passive socket that clients connect to
     */
    private DatagramSocket server2 = null;

    /**
     * Creates a new Responder thread.
     *
     * @param address Local address to bind to.
     * @param port Local port to bind to. 0 for random.
     */
    public STUNTServer(InetAddress address, int port) throws java.io.IOException {
        server = new ServerSocket(port, 5, address);
        server2 = new DatagramSocket(server.getLocalSocketAddress());
    }

    /**
     * Returns the local IP and port the server is listening on.
     * @return Server socket address
     */
    public SocketAddress getSocketAddress() {
        return server.getLocalSocketAddress();
    }

    private class TCPThread extends Thread {
        /**
        * Starts the responder thread that responds to TCP clients in a tight loop.
         */
        public void run() {
            try {
                while(true) {
                    Socket client = server.accept();
                    try {
                        // Using old API since there is not ObjectOutputChannel yet.
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(bos);
                        oos.writeObject(client.getRemoteSocketAddress());
                        oos.close();
                        client.getOutputStream().write(bos.toByteArray());
                        client.close();
                    } catch (Exception e) {
                        log.throwing("TCPThread", "run", e);
                        break;
                    } finally {
                        try { client.close(); } catch (Exception e) { }
                    }
                }
            } catch (Exception e) {
                log.throwing("TCPThread", "run", e);
            } finally {
                try { server.close(); } catch (Exception e) { }
            }
        }
    }

    private class UDPThread extends Thread {
        /**
        * Starts the responder thread that responds to TCP clients in a tight loop.
         */
        public void run() {
            byte[] buf = new byte[1500];
            DatagramPacket p = new DatagramPacket(buf, buf.length);
            try {
                while(true) {
                    server2.receive(p);
                    try {
                        // Using old API since there is not ObjectOutputChannel yet.
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutputStream oos = new ObjectOutputStream(bos);
                        oos.writeObject(p.getSocketAddress());
                        oos.close();
                        p.setData(bos.toByteArray());
                        server2.send(p);
                    } catch (Exception e) {
                        log.throwing("UDPThread", "run", e);
                        try { server2.close(); } catch (Exception e2) { }
                        break;
                    }
                }
            } catch (Exception e) {
                log.throwing("UDPThread", "run", e);
            } finally {
                try { server2.close(); } catch (Exception e) { }
            }
        }
    }

    public void run() {
        new TCPThread().start();
        new UDPThread().start();
    }


    /**
    *Starts a standalone server
    *
    * @param args Program arguments
     */
    public static void main(String args[]) {
        if (args.length != 2) {
            System.err.printf("Usage:\n\tjava STUNTServer ip port\n");
            System.exit(1);
        }

        try {
            STUNTServer r = new STUNTServer(InetAddress.getByName(args[0]), Integer.parseInt(args[1]));
            System.out.printf("STUNT Server: %s\n", r.getSocketAddress());
            r.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

